<?php

namespace App\Jobs;

use App\Models\StockCodes;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\Http;

class ComputeTemperature implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    public  $token;
    /**
     * Create a new job instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->token = config('lixingren.token');
    }

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {
        $codes = StockCodes::where('api','a')->get();
        $data = [];
        foreach ($codes as $key=> $value)
        {

            $res = $this->getOneIndexFundamental($value->code)[0];
            $data[] = [
                'id' => $value->id,
                'code' => $value->code,
                'title' => $value->title,
                'pe_ttm_y10_cv'=>$res['pe_ttm']['y10']['mcw']['cv'],
                'pe_ttm_y10_cvpos'=>$res['pe_ttm']['y10']['mcw']['cvpos'],
                'pb_y10_cv'=>$res['pb']['y10']['mcw']['cv'],
                'pb_y10_cvpos'=>$res['pb']['y10']['mcw']['cvpos'],
            ];
        }

        $data = array_map(function($item){
            return [
                'id' => $item['id'],
                'code' => $item['code'],
                'title' => $item['title'],
                'pe_temp'=>$item['pe_ttm_y10_cvpos']*100,
                'pb_temp'=>$item['pb_y10_cvpos']*100
            ];
        },$data);
        $this->storeData($data);
    }

    /**
     * 存储数据到数据库中
     * @param $data
     */
    protected function storeData($data)
    {
        foreach ($data as $value)
        {
            StockCodes::where('id',$value['id'])
                ->update([
                    'pe_temp' => $value['pe_temp'],
                    'pb_temp' => $value['pb_temp'],
                    'index_temperture'=> ($value['pe_temp']+$value['pb_temp'])/2,
                    'computed_at'=> Carbon::now()
                ]);
        }
    }

    /**
     * 获取单个指数信息
     * @param $code
     * @return mixed
     */
    protected function getOneIndexFundamental($code)
    {
        $response = Http::post('https://open.lixinger.com/api/a/index/fundamental',[
            'token' =>$this->token,
            'date'=>'latest',
            "stockCodes" => [
                $code
            ],
            'metricsList'=>[
                "pe_ttm.y10.mcw",
                "pe_ttm.mcw",
                "pb.mcw",
                "pb.y10.mcw",
            ]
        ]);
        return $response ['data'];
    }
}
